package com.khadi.testcase.util;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.khadi.testcase.view.model.HtmlFieldModel;
import com.khadi.testcase.view.model.IdValueModel;

public class HtmlObjectFinder {
	private static final String X_PATH = "X_PATH";

	private static final String PATIAL_LINK_TEXT = "PATIAL_LINK_TEXT";

	private static final String LINK_TEXT = "LINK_TEXT";

	private static final String CLASS_NAME = "CLASS_NAME";

	private static final String ID = "ID";

	private static final String NAME = "NAME";

	WebDriver driver;

	public static final String TAG_NAME = "TAG_NAME";

	public HtmlObjectFinder(WebDriver driver) {
		this.driver = driver;
	}

	public List<HtmlFieldModel> getHtmlFieldModelList(String searchByText,
			IdValueModel<String, String> searchBy) {

		List<HtmlFieldModel> list = new ArrayList<HtmlFieldModel>();

		for (WebElement webElement : getDriver().findElements(
				getBy(searchByText, searchBy))) {

			String elementName = webElement.getAttribute("name");

			String elementType = webElement.getAttribute("type");

			String elementId = webElement.getAttribute("id");
			String className = webElement.getAttribute("className");

			String value = webElement.getText();

			list.add(new HtmlFieldModel(elementName, elementType, elementId,
					value, className));

		}

		return list;

	}

	private By getBy(String searchByText, IdValueModel<String, String> searchBy) {
		String key = searchBy.getK();
		if (key.equals(TAG_NAME)) {
			return By.tagName(searchByText);
		}else if(key.equals(NAME)){
			return By.name(searchByText); 
		}else if(key.equals(ID)){
			 return By.id(searchByText);
		}else if(key.equals(CLASS_NAME)){
			return By.className(searchByText);
		}else if(key.equals(LINK_TEXT)){
			return By.linkText(searchByText);
		}else if(key.equals(PATIAL_LINK_TEXT)){
			return By.partialLinkText(searchByText);
		}
		return null;
	}

	public WebDriver getDriver() {
		return driver;
	}

	public static final List<IdValueModel<String, String>> getSearchByList() {

		List<IdValueModel<String, String>> searchBylist = new ArrayList<IdValueModel<String, String>>();

		searchBylist.add(getEntity(TAG_NAME, "Tag Name"));
		searchBylist.add(getEntity(NAME, "Name"));
		searchBylist.add(getEntity(ID, "id"));
		searchBylist.add(getEntity(CLASS_NAME, "Class Name"));
		searchBylist.add(getEntity(LINK_TEXT, "Link Text"));
		searchBylist.add(getEntity(PATIAL_LINK_TEXT, "Partial Link Text"));

		searchBylist.add(getEntity(X_PATH, "XPath"));
		return searchBylist;
	}

	private static IdValueModel<String, String> getEntity(String key,
			String value) {
		return new IdValueModel<String, String>(key, value);
	}

}
